#include "amexporter.h"
#include <stdio.h>
#include <stdlib.h>
#include "amutils.h"
#include <QtEndian>
#include <QMessageBox>

AMExporter::AMExporter(QObject *parent) : QObject(parent)
{
}

void AMExporter::write(QString filename, model * m)
{
    const char * fname = filename.toStdString().c_str();
    FILE * fout = fopen(fname, "wb");
    int c = m->vind_count;
    int vc = c*3;

    int rvc = qToBigEndian(vc);
    int rc = qToBigEndian(c);

    fwrite(&rvc, sizeof(int), 1, fout);
    fwrite(&rvc, sizeof(int), 1, fout);
    fwrite(&rc, sizeof(int), 1, fout);

    float tempVerts[vc];
    float tempNorms[vc];
    short indices[c];

    int vi, vn;
    for(int i = 0; i < c; i++) {
        vi = m->vinds[i]*3;
        vn = i*3;
        tempVerts[vn] = m->verts[vi];
        tempVerts[vn + 1] = m->verts[vi + 1];
        tempVerts[vn + 2] = m->verts[vi + 2];

        vi = m->ninds[i]*3;
        tempNorms[vn] = m->ninds[vi];
        tempNorms[vn + 1] = m->ninds[vi + 1];
        tempNorms[vn + 2] = m->ninds[vi + 2];

        indices[i] = qToBigEndian((short) i);
    }

    float vertices[vc];
    float normals[vc];

    for(int i = 0; i < vc; i+=3) {
        vertices[i] = AMUtils::revEndian(tempVerts[i]);
        vertices[i + 1] = AMUtils::revEndian(tempVerts[i + 1]);
        vertices[i + 2] = AMUtils::revEndian(tempVerts[i + 2]);

        normals[i] = AMUtils::revEndian(tempNorms[i]);
        normals[i + 1] = AMUtils::revEndian(tempNorms[i + 1]);
        normals[i + 2] = AMUtils::revEndian(tempNorms[i + 2]);
    }

    fwrite(vertices, sizeof(float), vc, fout);
    fwrite(normals, sizeof(float), vc, fout);
    fwrite(indices, sizeof(short), c, fout);

    fclose(fout);
}


